package com.gxuwz.attend.web.servlet;

import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Student;
import com.gxuwz.attend.service.Impl.StudentServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "studentServlet" , urlPatterns = "/student")
public class StudentServlet extends BaseHttpServlet{
    private final Logger logger= LoggerFactory.getLogger(DepartmentServlet.class);
    private final static String VIEW_ADD="/WEB-INF/views/student/student_add.jsp";
    private final static String VIEW_EDIT="/WEB-INF/views/student/student_edit.jsp";
    private final static String VIEW_LIST="/WEB-INF/views/student/student_list.jsp";
    private final static String ACTION_LIST="/student?action=list";
    private StudentServiceImpl studentService;
    @Override
    public void init() throws ServletException {
        super.init();
        studentService = AppContext.getBean(StudentServiceImpl.class);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("..................");
        System.out.println();
//1：接受请求参数action以及其他页面的参数值，按照约定，动作请求action依次为input、add、delete、get、edit、list.
        String action =req.getParameter("action");
        System.out.println("action:" + action);
        String view=ErrorPage_500;
        logger.info("request process starting"+action);
        try {
            //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
            switch (action) {
                case "input":
                    view = VIEW_ADD;
                    Student student = new Student();
                    student.setStuID("");
                    student.setClassID("");
                    student.setStuName("");
                    student.setSex("");
                    student.setAddress("");
                    student.setStuTel("");
                    student.setContact("");
                    student.setContactTel("");
                    req.setAttribute("student",student);
                    break;
                case "add":
                    student = new Student();
                    resolveRequestParameter(req,student);
                    studentService.insertStudent(student);
                    System.out.println("add-student:"+student);
                    //指定跳转路径
                    view = ACTION_LIST;
                    break;
                case "delete":

                    String id =req.getParameter("id");
                    studentService.deleteStudent(id);
                    System.out.println("delete-studentID:"+id);
                    view = ACTION_LIST;
                    break;
                case "get":

                    id =req.getParameter("id");
                    student = new Student();
                    student.setStuID(id);
                    System.out.println("get-studentID:"+id);
                    List<Student> studentList = new ArrayList<>();
                    studentList = studentService.queryStudent(student);
                    student = studentList.get(0);
                    view = VIEW_EDIT;
                    req.setAttribute("m",student);
                    break;
                case "edit":
                    student = new Student();
                    resolveRequestParameter(req,student);
                    System.out.println("edit:student : "+student);
                    studentService.updateStudent(student);
                    view = ACTION_LIST;
                    break;
                case "list":
                    System.out.println(11);
                    String stuName=req.getParameter("stuName11");
                    System.out.println("stuName:"+stuName);
                    if (stuName==null||stuName.isEmpty()){
                        List<Student> studentList1 = new ArrayList<>();
                        studentList1 = studentService.queryStudents();
                        view = VIEW_LIST;
                        req.setAttribute("list",studentList1);
                        break;
                    }else{
                        Student student1 = new Student();
                        student1.setStuName(stuName);
                        List<Student> studentList1 = new ArrayList<>();
                        studentList1 = studentService.queryStudent(student1);
                        view = VIEW_LIST;
                        req.setAttribute("list",studentList1);
                        break;
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
            req.setAttribute("message",e.getMessage());
            view =ErrorPage_500;
        }
        //3:页面跳转，默认转发方式
        super.doDispatch(req,resp,view);
    }

    /**
     * 解析request参数并转换为POJO对象
     * @param req
     */
    private void resolveRequestParameter(HttpServletRequest req,Object bean){
        Map<String,String[]> reqParameterMap= req.getParameterMap();
        Map<String,String[]> propertiesMap=new HashMap<String,String[]>();
        try {
            for (Map.Entry<String,String[]>  entry : reqParameterMap.entrySet()){
                String name =entry.getKey();
                String[] values=entry.getValue();
                //判断request参数是否对应JavaBean对象的属性
                Class propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType!=null) {
                    propertiesMap.put(name,values);
                }
            }
            //转换为POJO对象bean的属性值
            BeanUtils.populate(bean,propertiesMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("The property name could not be found",e);
        }

    }

}
